<?php

namespace app\admin\controller\platform\task;

use app\BaseController;
use app\model\platform\PlatformTaskContinuousEvaluationModel;
use app\model\platform\PlatformTaskModel;
use app\model\platform\PlatformTaskRatingScaleModel;
use app\model\platform\PlatformTaskUnitModel;
use app\model\TaskModel;
use app\model\UserModel;
use think\App;

class EndTask extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new PlatformTaskModel();
    }

    /**
     * 发布人选择器
     * @return bool|string
     */
    public function publisherSelector(): bool|string
    {
        try {
            $TaskModel = new TaskModel();
            $uid = $TaskModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['channel','=',2]
            ])->distinct(true)->column('uid');
            if (!empty($uid)) {
                $UserModel = new UserModel();
                $data = $UserModel->field('id,name')->where('id','in',$uid)->select()->toArray();
            }else{
                $data = [];
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $unit_task_where = [];
            if (!empty($param['name'])){
                $unit_task_where[] = ['name','like','%'.$param['name'].'%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['submit_time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['submit_time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['submit_time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['uid'])){
                $unit_task_where[] = ['uid','=',$param['uid']];
            }
            if (!empty($param['level'])){
                $UserModel = new UserModel();
                $uid = $UserModel->where([
                    ['company_id','=',$this->userData['company_id']],
                    ['areas_id','=',$this->userData['areas_id']],
                    ['level','=',$param['level']]
                ])->column('id');
                if (count($uid) > 0){
                    $PlatformTaskModel = new PlatformTaskModel();
                    $task_id = $PlatformTaskModel->where('uid','in',$uid)->column('id');
                    if (count($task_id) > 0){
                        $where[] = ['task_id','in',$task_id];
                    }else{
                        $where[] = ['id','=',-1];
                    }
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            if (!empty($unit_task_where)){
                $TaskModel = new TaskModel();
                $unit_task_id = $TaskModel->where($unit_task_where)->column('id');
                if (count($unit_task_id) > 0){
                    $where[] = ['unit_task_id','in',$unit_task_id];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $PlatformTaskRatingScaleModel = new PlatformTaskRatingScaleModel();
            $PlatformTaskContinuousEvaluationModel = new PlatformTaskContinuousEvaluationModel();
            $task_id = $this->mode->where('status','=',3)->column('id');
            $where[] = ['task_id','in',$task_id];
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $query = $PlatformTaskUnitModel->where($where);
            $data = $query->with([
                'UnitTask' => function ($query) {
                    $query->with(['userName']);
                },
                'task' => function ($query) {
                    $query->with(['user']);
                }
            ])->order('id', 'desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$v) {
                $v['role_name'] = match ($v['user_level']) {
                    1 => '省级平台管理员',
                    2 => '市级平台管理员',
                    3 => '区级平台管理员'
                };
                //量表
                $TaskRatingScaleList = $PlatformTaskRatingScaleModel->where('task_id','=', $v['task_id'])
                    ->with([
                        'ratingScale',
                    ])->select()->toArray();
                $factorList = $PlatformTaskContinuousEvaluationModel->where('task_id','=', $v['task_id'])
                    ->with([
                        'RatingScale', 'RatingScaleFactor'
                    ])->select()->toArray();
                $factorData = [];
                foreach ($factorList as $item) {
                    $factorData[$item['rating_scale_id']][] = [
                        'factor_id' => $item['factor_id'],
                        'factor_name' => $item['factor_name'],
                        'rating_scale_id' => $item['rating_scale_id'],
                        'rating_scale_name' => $item['rating_scale_name'],
                    ];
                }
                $rating_scale = [];
                foreach ($TaskRatingScaleList as $item) {
                    $rating_scale[] = [
                        'id' => $item['rating_scale_id'],
                        'name' => $item['rating_scale_name'],
                        'factor' => $factorData[$item['rating_scale_id']] ?? []
                    ];
                }
                $v['rating_scale'] = $rating_scale;
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 单位任务详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');//单位任务id
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $PlatformTaskRatingScaleModel = new PlatformTaskRatingScaleModel();
            $PlatformTaskContinuousEvaluationModel = new PlatformTaskContinuousEvaluationModel();
            $info = $PlatformTaskUnitModel->with([
                'UnitTaskInfo' => function ($query) {
                    $query->with(['userName']);
                },
                'task' => function ($query) {
                    $query->with(['user']);
                }
            ])->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            //量表
            $TaskRatingScaleList = $PlatformTaskRatingScaleModel->where('task_id','=', $info['task_id'])
                ->with([
                    'ratingScale',
                ])->select()->toArray();
            $factorList = $PlatformTaskContinuousEvaluationModel->where('task_id','=', $info['task_id'])
                ->with([
                    'ContinuityRatingScale', 'RatingScaleFactor'
                ])->select()->toArray();
            $factorData = [];
            foreach ($factorList as $item) {
                $factorData[$item['rating_scale_id']][] = [
                    'factor_id' => $item['factor_id'],
                    'factor_name' => $item['factor_name'],
                    'rating_scale_id' => $item['continuity_rating_scale_id'],
                    'rating_scale_name' => $item['continuity_rating_scale_name'],
                ];
            }
            $rating_scale = [];
            foreach ($TaskRatingScaleList as $item) {
                $rating_scale[] = [
                    'id' => $item['rating_scale_id'],
                    'name' => $item['rating_scale_name'],
                    'factor' => $factorData[$item['rating_scale_id']] ?? []
                ];
            }
            $info['rating_scale'] = $rating_scale;
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}